package com.fantasybaby.util;

import redis.clients.jedis.Jedis;

public class RedisConnect {
	private static ThreadLocal<Jedis> _jedis = new ThreadLocal<Jedis>();
	private static Jedis jedis;
	private static String uri;
	private static int port;
	public RedisConnect(){
		
	}
	public RedisConnect(String _uri){
		 uri = _uri;
		 jedis = _jedis.get();
		if (jedis == null) {
			jedis = new Jedis(uri);
			_jedis.set(jedis);
		}
	}
	public RedisConnect(String _uri,int _port){
		 uri = _uri;
		 port = _port;
		 jedis = _jedis.get();
		if (jedis == null) {
			jedis = new Jedis(uri,port);
			_jedis.set(jedis);
		}
	}
	public  Jedis getJedis() throws Exception{
		 jedis = _jedis.get();
		 if (jedis == null) {
			 reConnectJedis();
		}
		return jedis;
	}
	public static void closeJedis(){
		jedis = _jedis.get();
		if (jedis != null) {
			jedis.close();
			_jedis.remove();
		}
	}
	public static void reConnectJedis() throws Exception{
		if (uri != null) {
			if (port == 0) {
				jedis = new Jedis(uri);
			}else{
				jedis = new Jedis(uri,port);
			}
			
			_jedis.set(jedis);
		}else{
			throw new Exception("There is no url to connect");
		}
	}
	public void setUri(String _uri){
		uri = _uri;
	}
	
}
